package org.herrdommel.webpagechecker.pages;

import java.util.Calendar;
import java.util.GregorianCalendar;

import org.herrdommel.webpagechecker.util.WPCDataSource;
import org.herrdommel.webpagechecker.util.sqlentities.Page;
import org.htmlcleaner.TagNode;

import android.os.Bundle;
import android.support.v4.app.Fragment;

public abstract class AbstractPage extends Fragment {

	private WPCDataSource datasource;
	protected static final int STEP_INIT = 0x0;
	protected static final int STEP_ONE = 0x1;
	protected static final int STEP_TWO = 0x2;
	protected static final int STEP_THREE = 0x3;
	protected static final int STEP_FOUR = 0x4;
	protected static final int STEP_FINISH = 0x100;
	protected int currentStep = STEP_INIT;

	public abstract void onRadarLoaded(TagNode content);

	/**
	 * Checks if there is data cached
	 * @param page The name of the page to check for
	 * @param timeSpan The int value from {@link Calendar} fields. Example: {@link Calendar}.WEEK_OF_YEAR
	 * @return
	 */
	protected String checkCache(final String page, final int timeSpan) {
		final GregorianCalendar now = new GregorianCalendar();
		if (datasource == null) {
			datasource = new WPCDataSource(getActivity());
			datasource.open();
		}
		final Page res = datasource.getPage(page);
		if (res == null) {
			return null;
		}
		final GregorianCalendar cachetime = new GregorianCalendar();
		cachetime.setTimeInMillis(Long.parseLong(res.getCachetime()));
		final int nowTime = now.get(timeSpan);
		final int cacheTime = cachetime.get(timeSpan);
		if (nowTime <= cacheTime && cachetime.before(now)) {
			return res.getResult();
		}
		return null;
	}

	protected void saveToCache(final String page, final String result) {
		final Page res = datasource.getPage(page);
		if (res != null) {
			datasource.updatePage(page, result);
		} else {
			datasource.createPage(page, result);
		}
	}

	@Override
	public void onActivityCreated(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (datasource == null) {
			datasource = new WPCDataSource(getActivity());
		}
		datasource.open();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (datasource != null) {
			datasource.close();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		if (datasource == null) {
			datasource = new WPCDataSource(getActivity());
		}
		datasource.open();
	}

}
